<template>
  <div id="app-container" style="margin: 20px">
    <!--条件查询表单-->
    <el-form :model="queryTrainingLevelDTO" :inline="true" ref="trainingLevel" :rules="rules">

      <el-form-item label="靶场名称" >
        <el-input v-model="queryTrainingLevelDTO.trainingName" size="small" style="width: 300px" placeholder="请输入靶场名称"/>
      </el-form-item>

      <el-form-item label="靶场种类" prop="trainingType" >
        <el-input v-model="queryTrainingLevelDTO.trainingType" size="small"  style="width: 300px" placeholder="靶场种类，若为一级分类请输入 0"/>
      </el-form-item>

    </el-form>
    <el-form :inline="true">
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryTrainingLevelDTO.createTimeStart"
          size="small"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"/>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="queryTrainingLevelDTO.createTimeEnd"
          size="small"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="pageListQuery()">查询</el-button>
        <el-button plain icon="el-icon-refresh" style="margin-left: 0" @click="resetData()">清空</el-button>

      </el-form-item>
    </el-form>

    <el-form :inline="true">
      <router-link to="/trainingLevel/add">
        <el-button type="primary" plain icon="el-icon-plus" size="small">新增</el-button>
      </router-link>
      <el-button type="warning" plain icon="el-icon-delete" size="small" @click="deleteBySelect">批量删除</el-button>
      <el-button type="danger" plain icon="el-icon-download" size="small" @click="handleExport">导出</el-button>
    </el-form>

    <!--数据显示列表-->
    <el-table
      :data="trainingLevelList"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="45"
        align="center"/>
      <el-table-column label="序号" width="60" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!--      <el-table-column prop="id" label="靶场分级ID" width="90" align="center"/>-->

<!--      <el-table-column prop="trainingId" label="靶场ID" width="90" align="center"/>-->

      <el-table-column prop="trainingName" label="靶场名称" width="300" align="center"/>

      <el-table-column prop="trainingType" label="靶场种类" width="300" align="center"/>

      <el-table-column prop="createTime" label="创建时间" width="200" align="center"/>
      <el-table-column prop="updateTime" label="更新时间" width="200" align="center"/>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <router-link :to="'/trainingLevel/update/'+scope.row.id">
            <el-button
              type="text"
              icon="el-icon-edit"
              size="mini">编辑</el-button>
          </router-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import training_level from '../../api/training_level'
import axios from 'axios'
import fileDownload from 'js-file-download'

export default {
  data() {
    const typeCheck = (rule, value, callback) => {
        if ( value !=0 && value!=null) {
          training_level.nameIsExit2(value).then(res => {
            if (res.data === true) {
              callback()
            } else {
              callback(new Error('该靶场种类不存在'))
            }
          })
        }else {
          callback()
        }
    }

      // else {
        // 新增
        // 给后端发起一个请求，查询该用户名是否存在
      //   training_level.nameIsExit(value).then(res => {
      //     if (res.data === true) {
      //       callback()
      //     } else {
      //       if (value!=0){
      //         callback(new Error('该靶场种类不存在'))
      //       }
      //       else {
      //         callback()
      //       }
      //     }
      //   })
      // }
    // }
    return {
      queryTrainingLevelDTO: {},
      trainingLevelList: [],
      currentPage: 1,
      pageSize: 10,
      total: 1,
      ids: [],
      multipleSelection: [''],
      rules: {
        trainingType: [
          { required: false, message: '请输入靶场种类', trigger: 'blur' },
          { validator: typeCheck, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initDate()
  },
  methods: {
    pageListQuery() {
      this.$refs['trainingLevel'].validate((valid) => {
        if (valid) {
         this.initDate()
        } else {
          this.$message.error('校验不通过！请重试！')
          console.log('error submit!!')
          return false
        }
      })
    },
    resetData() {
      this.queryTrainingLevelDTO = {}
      this.initDate()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.initDate()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.initDate()
    },
    handleDelete(id) {
      this.$confirm('是否确定删除', '提示信息', { type: 'warning' }).then(() => {
        this.ids.push(id)
        training_level.deleteOneTrainingLevel(this.ids).then(response => {
          this.$message.success('删除成功')
          this.initDate()
          this.ids = []
        })
      }).catch(() => {
        this.$message.info('取消删除操作')
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = []
      for (let i = 0; i < val.length; i++) {
        if (this.multipleSelection.indexOf(val[i].id) === -1) {
          this.multipleSelection.push(val[i].id)
        }
      }
      console.log(this.multipleSelection)
    },
    deleteBySelect() {
      this.$confirm('是否确定删除', '提示信息', { type: 'warning' }).then(() => {
        training_level.deleteSelectTrainingLevel(this.multipleSelection).then(response => {
          this.$message.success('删除成功')
          this.multipleSelection = []
          this.initDate()
        })
      }).catch(() => {
        this.$message.info('取消删除操作')
      })
    },
    handleExport() {
      axios({
        method: 'post',
        url: 'http://localhost:8080/trainingLevel/export',
        responseType: 'blob',
        data: this.queryTrainingLevelDTO
      }).then(res => {
        if (res && res.data) {
          fileDownload(res.data, '靶场分级信息.xlsx')
        }
      })
    },
    initDate() {
      training_level.listPage(this.currentPage, this.pageSize, this.queryTrainingLevelDTO).then(response => {
        this.trainingLevelList = response.data.data
        this.total = response.data.total
      })
    }
  }
}
</script>
